package com.itany.shop.servlet;

import com.itany.shop.entity.Product;
import com.itany.shop.exception.ServiceException;
import com.itany.shop.factory.ObjectFactory;
import com.itany.shop.service.ProductService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * Author:shixiaojun@itany.com
 * Date:2022/4/15 14:12
 * Version:1.0-SNAPSHOT
 * Description:
 */
@WebServlet("*.product")
public class ProductServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        request.setCharacterEncoding("utf-8");
//        response.setContentType("text/html;charset=utf-8");
        String path = request.getServletPath();
        if("/findAll.product".equals(path)){
            findAll(request,response);
        }
    }

    public void findAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ProductService productService = (ProductService) ObjectFactory.getObject("productService");

        try {
            List<Product> products = productService.findAll();
            // 在开发中,遇到存储数据的时候,尽可能的将数据存储到尽可能小的作用域的
            // 即:能存放在request,就不要存放到session中
            // 作用域大的生存时间较长,即数据在服务器中存在时间较长
            // 对于服务器压力就较大
            request.setAttribute("products",products);
            request.getRequestDispatcher("/jsp/main.jsp").forward(request,response);
        } catch (ServiceException e) {
            e.printStackTrace();
            request.getRequestDispatcher("/jsp/main.jsp").forward(request,response);
        }

    }
}
